package evan.curtis.beersnob;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import evan.curtis.beersnob.util.Constants;
import evan.curtis.beersnob.util.DatabaseFunctions;
import evan.curtis.beersnob.util.Vibration;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SearchFragment extends Fragment implements OnKeyListener {

	private View mContentView;
	private MainActivity mActivity;
	private EditText searchBar;
	private LinearLayout resultsLayout;
	private JSONArray databaseValues = new JSONArray();

	// ------------------------------------------------------------------------------------/

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mContentView = inflater.inflate(R.layout.search_layout, container,
				false);

		mActivity = (MainActivity) this.getActivity();

		setHasOptionsMenu(true);

		initTextViews();

		return mContentView;
	}

	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem addBeer = menu.add("Add beer");

		addBeer.setOnMenuItemClickListener(addBeerListener);

	}

	// ------------------------------------------------------------------------------------/

	public void initTextViews() {
		searchBar = (EditText) mContentView.findViewById(R.id.search_value);
		searchBar.setOnKeyListener(this);
		resultsLayout = (LinearLayout) mContentView
				.findViewById(R.id.resultsLayout);
		int c = getResources().getColor(R.color.results_layout_background);
		resultsLayout.setBackgroundColor(c);

	}

	// ------------------------------------------------------------------------------------/

	public void updateTextViews() throws JSONException {

		resultsLayout.removeAllViews();

		// check if there are no results
		if (databaseValues.length() == 0) {
			TextView t = new TextView(mActivity);
			t.setText("No matches found.");
			resultsLayout.addView(t);
		}

		// if there are results, print them
		for (int i = 0; i < databaseValues.length(); i++) {
			JSONObject json_data = databaseValues.getJSONObject(i);

			final int id = json_data.getInt("id");
			final String name = json_data.getString("name");
			final String brewer = json_data.getString("brewer");
			final String style = json_data.getString("style");
			final int reviewCount = json_data.getInt("reviews");
			final int rating = json_data.getInt("avg_rating");

			// inflate layout to display results
			RelativeLayout rl = new RelativeLayout(mActivity);
			LayoutInflater inflater = (LayoutInflater) mActivity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View volumeView = inflater.inflate(R.layout.card, rl);

			// initialize TextViews
			TextView nameText = (TextView) volumeView.findViewById(R.id.name);
			TextView brewerText = (TextView) volumeView
					.findViewById(R.id.brewer);
			TextView ratingText = (TextView) volumeView
					.findViewById(R.id.rating);
			TextView reviewsText = (TextView) volumeView
					.findViewById(R.id.reviewCount);

			// set Text
			nameText.setText(name);
			brewerText.setText(brewer);
			ratingText.setText(Integer.toString(rating));
			reviewsText.setText(Integer.toString(reviewCount));

			volumeView.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View arg0) {
					// change color of TextView and vibrate to show user that it
					// has been clicked

					Vibration.vibrate(20, mActivity);

					// create new Intent and pass values, then start activity
					Intent myIntent = new Intent(mActivity, BeerView.class);
					myIntent.putExtra("id", id);
					myIntent.putExtra("name", name);
					myIntent.putExtra("brewer", brewer);
					myIntent.putExtra("style", style);
					myIntent.putExtra("rating", rating);
					startActivity(myIntent);

					return false;
				}

			});

			resultsLayout.addView(volumeView);

		}

	}

	// ------------------------------------------------------------------------------------/

	public boolean onKey(View view, int keyCode, KeyEvent event) {

		EditText searchBar = (EditText) mActivity
				.findViewById(R.id.search_value);

		if (keyCode == EditorInfo.IME_ACTION_SEARCH
				|| keyCode == EditorInfo.IME_ACTION_DONE
				|| event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

			if (!event.isShiftPressed()) {
				// Log.v("AndroidEnterKeyActivity","Enter Key Pressed!");
				switch (view.getId()) {
				case R.id.search_value:
					new dbOperation().execute(Constants.SEARCH_BY_NAME,
							searchBar.getText().toString());
					break;

				}
				return true;
			}

		}
		return false;

	}

	// ------------------------------------------------------------------------------------/

	private class dbOperation extends AsyncTask<String, Void, String> {

		JSONArray returnValue = null;
		String filename;

		@Override
		protected String doInBackground(String... params) {

			filename = params[0];

			if (filename.equals(Constants.INSERT_BEER)) {
				String name = null;
				String brewer = null;
				String style = null;
				String rating = null;
				String comment = null;

				try {
					name = URLEncoder.encode(params[1], "UTF-8");
					brewer = URLEncoder.encode(params[2], "UTF-8");
					style = URLEncoder.encode(params[3], "UTF-8");

					if (params[4].equals("")) {
						rating = "0";
					} else {
						rating = URLEncoder.encode(params[4], "UTF-8");
					}
					
					comment = URLEncoder.encode(params[5], "UTF-8");
					
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				String query = "?name=" + name + "&brewer=" + brewer
						+ "&style=" + style + "&rating=" + rating + "&comment="
						+ comment;

				returnValue = DatabaseFunctions.getJSONArray(filename, query);

			} else if (filename.equals(Constants.SEARCH_BY_NAME)) {
				String query = null;
				try {
					query = "?name=" + URLEncoder.encode(params[1], "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				returnValue = DatabaseFunctions.getJSONArray(filename, query);
			}

			return null;

		}

		@Override
		protected void onPostExecute(String result) {

			if (filename.equals(Constants.SEARCH_BY_NAME)) {
				databaseValues = returnValue;
				try {
					updateTextViews();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}
	}

	// ---------------------------------------------------------------------------------/

	private OnMenuItemClickListener addBeerListener = new OnMenuItemClickListener() {

		public boolean onMenuItemClick(MenuItem arg0) {

			final AlertDialog dialog = new AlertDialog.Builder(mActivity)
					.create();
			dialog.setTitle("Add beer");
			LinearLayout linear = new LinearLayout(mActivity);
			linear.setOrientation(LinearLayout.VERTICAL);
			dialog.setView(linear);
			LayoutInflater inflater = (LayoutInflater) mActivity
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View volumeView = inflater
					.inflate(R.layout.add_beer_layout, linear);

			final EditText nameField = (EditText) volumeView
					.findViewById(R.id.name);
			final EditText brewerField = (EditText) volumeView
					.findViewById(R.id.brewer);
			final EditText styleField = (EditText) volumeView
					.findViewById(R.id.style);
			final EditText ratingField = (EditText) volumeView
					.findViewById(R.id.rating);
			final EditText commentField = (EditText) volumeView
					.findViewById(R.id.comment);

			dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "OK",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							String name = nameField.getText().toString();
							String brewer = brewerField.getText().toString();
							String style = styleField.getText().toString();
							String rating = ratingField.getText().toString();
							String comment = commentField.getText().toString();

							new dbOperation().execute(Constants.INSERT_BEER,
									name, brewer, style, rating, comment);

							dialog.cancel();

						}
					});

			dialog.show();

			return false;
		}

	};

}
